package com.sofwin.controller;

import com.sofwin.Constants;
import com.sofwin.dto.ResourceDto;
import com.sofwin.pojo.SysLoginLog;
import com.sofwin.pojo.SysUser;
import com.sofwin.service.LoginLogService;
import com.sofwin.service.ResourceService;
import com.sofwin.service.UserService;
import com.sofwin.util.CustomerUtil;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @packageName: com.sofwin.controller
 * @author: andyliu
 * @date: 2022/5/6 14:49
 * @email 115176513@qq.com
 * @description: TODO
 */
@Controller
public class LoginAction {
    @Autowired
    private UserService userService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private LoginLogService loginLogService;
    @GetMapping("index")
    public String toIndex(HttpSession session, ModelMap map){
        Subject subject = SecurityUtils.getSubject();
        String loginName = subject.getPrincipal().toString();
        SysUser user = userService.checkLogin(loginName);
        session.setAttribute(Constants.CURRENT_USER,user);
        Integer roleId = user.getRoleId();
        List<ResourceDto> resources = resourceService.queryResourceByRoleIds(roleId);
        map.put("resources",resources);
        return "index";
    }
    @PostMapping("login")
    public String login(HttpServletRequest request,SysUser user, HttpSession session, String yzm){
        String sessionYzm = session.getAttribute("code").toString();
        if(!yzm.toUpperCase().equals(sessionYzm.toUpperCase())){
            session.setAttribute("msg","验证码错误");
            return "redirect:login.jsp";
        }
        // 获取到当前登录的主体
       Subject subject= SecurityUtils.getSubject();
       UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(),user.getPassword());
       // 调用shiro的登录
        // 自动调用realm中的认证方法
        int flag=0;
        String msg="";
        try {
            subject.login(token);
            // 调用realm后如果认证成功，正常执行，如果认证失败，抛出对应异常
        }catch(UnknownAccountException exception){
           flag=1;
           msg="用户名不存在";
            // 认为没有当前账户
            session.setAttribute("msg",msg);
            return "redirect:login.jsp";
        }catch (IncorrectCredentialsException exception){
            // 密码错误
            flag=2;
            msg="密码错误";
            session.setAttribute("msg",msg);
            return "redirect:login.jsp";
        }catch (LockedAccountException exception){
            flag=3;
            // 账户锁定
        }finally{
            SysLoginLog log = new SysLoginLog();
            log.setLoginIp(CustomerUtil.getIpAddress(request));
            log.setChrome(CustomerUtil.browserName(request));
            log.setSysos(CustomerUtil.osName(request));
            log.setStatus(flag);
            log.setLoginMsg(flag==0?"登录成功":msg);
            if(flag==0){
                SysUser sysUser = userService.checkLogin(user.getLoginName());
                log.setUserId(sysUser.getUserId());
            }
            loginLogService.saveLoginLog(log);
        }
//        if(userLogin!=null){
//            session.setAttribute(Constants.CURRENT_USER,userLogin);
//            return "redirect:index";
//        }

        return "redirect:index";
    }
    @GetMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:login.jsp";
    }
}
